<template>
  <div class="app-container">
    <el-card class="drug-inventory-card">
      <div slot="header" class="clearfix">
        <span>💊 药品库存管理</span>
        <div class="header-buttons">
          <el-button type="primary" size="mini" @click="handleAdd">新增药品</el-button>
        </div>
      </div>
      
      <!-- 药品列表 -->
      <el-table v-loading="loading" :data="drugList">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="medicineName" label="药品名称" align="center" />
        <el-table-column prop="stockQuantity" label="库存" align="center">
          <template slot-scope="scope">
            <span :class="getStockClass(scope.row.stockQuantity)">
              {{ scope.row.stockQuantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="visibleUserNames" label="可见用户" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" align="center" width="100" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.pageNum"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="total, prev, pager, next, jumper"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑药品对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="handleDialogClose">
      <el-form ref="drugForm" :model="currentDrug" :rules="rules" label-width="80px">
        <el-form-item label="药品名称" prop="medicineName">
          <el-input v-model="currentDrug.medicineName" placeholder="请输入药品名称"/>
        </el-form-item>
        <el-form-item label="库存数量" prop="stockQuantity">
          <el-input-number v-model="currentDrug.stockQuantity" :min="0" controls-position="right"/>
        </el-form-item>
        
        <el-form-item label="可见用户" prop="visibleUserIds">
          <treeselect
            v-model="currentDrug.visibleUserIds"
            :options="userOptions"
            :normalizer="userNormalizer"
            :show-count="true"
            placeholder="请选择可见用户"
            :multiple="true"
            value-consists-of="LEAF_PRIORITY" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDrug">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMedicine, listMedicineByAuth, getMedicine, addMedicine, updateMedicine, delMedicine } from "@/api/crm/medicine";
import { deptUserTree } from "@/api/crm/user";
import { listUser } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Medicine",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        medicineName: undefined,
        stockQuantity: undefined
      },
      // 分页参数
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      // 药品列表
      drugList: [],
      // 对话框相关
      dialogVisible: false,
      dialogTitle: "",
      // 当前编辑的药品
      currentDrug: {
        medicineId: undefined,
        medicineName: "",
        stockQuantity: 0,
        visibleUserIds: []
      },
      // 用户选项
      userOptions: undefined,
      // 表单验证规则
      rules: {
        medicineName: [{ required: true, message: "药品名称不能为空", trigger: "blur" }],
        stockQuantity: [{ required: true, message: "库存数量不能为空", trigger: "blur" }]
        // visibleUsers 不再是必填项，用户可以选择对所有人可见
      }
    };
  },
  created() {
    this.getDrugList();
    this.getUserOptions();
  },
  methods: {
    /** 查询药品列表 */
    getDrugList() {
      this.loading = true;
      // 使用权限控制查询接口
      listMedicineByAuth(this.queryParams).then(response => {
        this.drugList = response.rows;
        this.pagination.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    /** 分页操作 */
    handlePageChange(val) {
      this.pagination.pageNum = val;
      this.getDrugList();
    },
    
    /** 查询部门和用户树结构 */
    getUserOptions() {
      deptUserTree().then(response => {
        this.userOptions = response.data;
      });
    },
    
    /** 用户树节点格式化 */
    userNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      };
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.dialogTitle = "添加药品";
      this.currentDrug = {
        medicineId: undefined,
        medicineName: "",
        stockQuantity: 0,
        visibleUserIds: []
      };
      this.dialogVisible = true;
    },
    
    /** 编辑按钮操作 */
    handleEdit(row) {
      getMedicine(row.medicineId).then(response => {
        this.currentDrug = response.data;
        this.dialogTitle = "修改药品";
        this.dialogVisible = true;
      });
    },
    
    /** 提交按钮 */
    submitDrug() {
      this.$refs["drugForm"].validate(valid => {
        if (valid) {
          // 过滤掉部门节点，只保留用户节点
          if (this.currentDrug.visibleUserIds) {
            // 假设用户ID通常比较小（< 100000），部门ID比较大
            this.currentDrug.visibleUserIds = this.currentDrug.visibleUserIds.filter(id => id < 100000);
          }
          
          if (this.currentDrug.medicineId) {
            updateMedicine(this.currentDrug).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialogVisible = false;
              this.getDrugList();
            });
          } else {
            addMedicine(this.currentDrug).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
              this.getDrugList();
            });
          }
        }
      });
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除药品"' + row.medicineName + '"？').then(function() {
        return delMedicine(row.medicineId);
      }).then(() => {
        this.getDrugList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    
    /** 对话框关闭 */
    handleDialogClose() {
      this.resetForm("drugForm");
    },
    
    /** 根据库存数量获取样式类 */
    getStockClass(stock) {
      if (stock === 0) {
        return "zero";
      } else if (stock < 50) {
        return "low";
      } else {
        return "ok";
      }
    },
    
    }
};
</script>

<style scoped lang="scss">
.drug-inventory-card {
  .header-buttons {
    float: right;
  }
  
  .query-form {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  // 库存状态样式
  .ok {
    color: #1b7d1b;
  }
  
  .low {
    color: #a40000;
  }
  
  .zero {
    color: #9a5a00;
  }
}
</style>

// 隐藏上传按钮样式
::v-deep.hide .el-upload--picture-card {
  display: none;
}
</style>